package com.lecture.java8.test.a;

public class Mugs {
    public static void main(String[] args) {
        String source = "fgwwwabcdefgwwwwww888fgwww";
        String matchStr = "fgwww";
        String replacement = "22222222";
        System.out.println(replaceRaw(source,matchStr,replacement));
        System.out.println(replaceRaw2(source,matchStr,replacement));
        System.out.println(replaceRaw3(source,matchStr,replacement));


        StringBuilder replaceStr = new StringBuilder(source);
        System.out.println(replaceStr.replace(1,3,"888888"));
        System.out.println("---------------");
        String a = "a-b-c-a-b-c-a-d-d-d";
        System.out.println(a.replace("a","0"));
    }


    public static String replaceRaw(String source,String matchStr,String replacement){

        String replaceStr = source;
        int matchLen = matchStr.length();
        int i = replaceStr.indexOf(matchStr);

        while(i>=0){
            replaceStr = replaceStr.substring(0,i)+""+replacement+""+replaceStr.substring(i + matchLen);
            i = replaceStr.indexOf(matchStr);
        }
        return replaceStr;
    }

    public static String replaceRaw2(String source, String matchStr, String replacement) {

        if (source == null || source.isEmpty()) {
            return "";
        }
        if (matchStr == null || matchStr.isEmpty()) {
            return source;
        }

        StringBuilder replaceStr = new StringBuilder(source);
        int matchLen = matchStr.length();
        int i = replaceStr.indexOf(matchStr);

        while (i >= 0) {
            replaceStr.replace(i, i + matchLen, replacement);
            i = replaceStr.indexOf(matchStr, i + replacement.length());
        }
        return replaceStr.toString();
    }

    public static String replaceRaw3(String source, String matchStr, String replacement) {
        if (source == null || source.isEmpty()) {
            return "";
        }
        if (matchStr == null || matchStr.isEmpty()) {
            return source;
        }

        StringBuilder sb = new StringBuilder(source);
        int matchLen = matchStr.length();
        int index = 0;

        while ((index = sb.indexOf(matchStr, index)) >= 0) {
            sb.replace(index, index + matchLen, replacement);
            index += replacement.length(); // 更新索引以跳过已替换的部分
        }

        return sb.toString();
    }

}
